package com.example.web.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.utils.SystemConstant;
import com.example.web.system.entity.LiveUser;
import com.example.web.system.entity.SysUser;
import com.example.web.system.mapper.LiveUserMapper;
import com.example.web.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private LiveUserMapper liveUserMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Integer userType = Integer.parseInt(username.substring(username.indexOf(":")+1));
        //获取用户名
        username=username.substring(0,username.indexOf(":"));

        //物业身份查询
        if(userType==SystemConstant.USER_TYPE_WUZHU){
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(SysUser::getUsername,username);
            SysUser user = sysUserMapper.selectOne(queryWrapper);
            if(Objects.isNull(user)){
                throw  new RuntimeException("用户名错误");
            }
            return user;
        }else if (userType== SystemConstant.USER_TYPE_YEZHU){
            QueryWrapper<LiveUser> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(LiveUser::getUsername,username);
            LiveUser user = liveUserMapper.selectOne(queryWrapper);
            if(Objects.isNull(user)){
                throw new RuntimeException("用户名错误");
            }
            return user;
        }else {
            return null;
        }
    }
}
